<template>
    <div class="wrapper">
		
		<div class="util">
			<el-button type="primary" class="add-button" plain @click="add(0, 1)" style="margin-right: 200px; margin-left: 20px;">添加商品</el-button>
            <span>商品类别：</span>
            <el-tree-select
			    v-model="searchCategory"
			    :data="categoryList"
			    :check-strictly="false"
				:props="TreeSelectProps"
				:multiple="false"
			    :render-after-expand="false"
                @change="getByCategoryId"
			    style="width: 240px;"
			  >
                <template #header>
                    <el-option
                        value="-1"
                        label="所有类别"
                    >
                    </el-option>
                </template>
            
            </el-tree-select>
			<span style="margin-left: 300px;">商品名称：</span>
			<el-input
				style="width: 260px;"
				placeholder="商品名称"
				v-model="searchValue"
			>
				<template #append>
					<el-button :icon="Search" @click="search()">
					</el-button>
				</template>
			</el-input>
		</div>
		
		<div class="main">
			<el-table
				:data="tableData.records"
				row-key="id"
				:header-cell-style="{background:'#F3F4F7',color:'#555',}"
			>
				<el-table-column label="商品图片">
					<template #default="scope">
						<el-image 
							:src="getImagePathFirst(scope.row.imagePathList)"
							:zoom-rate="1.2"
							:max-scale="7"
							:min-scale="0.2"
							:preview-src-list="getImagePath(scope.row.imagePathList)"
							:preview-teleported="true"
							style="width: 80px; height: 80px;"
							fit="cover"
						></el-image>
					</template>
				</el-table-column>
				<el-table-column label="商品名称" prop="name" show-overflow-tooltip></el-table-column>
				<el-table-column label="商品价格" class-name="el-table-price">
					<template #default="scope">
						{{scope.row.price}}￥
					</template>
				</el-table-column>
				<el-table-column label="库存数量" prop="store"></el-table-column>
				<el-table-column label="销售额" prop="sales"></el-table-column>
				<el-table-column label="商品类别" prop="categoryId" :formatter="categoryFormatter"></el-table-column>
				<el-table-column label="商品状态">
					<template #default="scope">
						<el-tag v-if="scope.row.status === true" type="success">正常</el-tag>
						<el-tag v-else type="info">已下架</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="200px">
					<template #default="scope">
						
						<template v-if="scope.row.status">
							<el-button v-if="scope.row.status" type="primary" size="small" plain @click="update(scope.row.id)">修改</el-button>
							<el-button  v-if="scope.row.status" type="primary" size="small" plain @click="updateStatus(scope.row.id, 0)">下架</el-button>
						</template>
						<el-button  v-if="!scope.row.status" type="success" size="small" plain @click="updateStatus(scope.row.id, 1)">上架</el-button>
						<el-button type="danger" size="small" plain @click="del(scope.row.id)">删除</el-button>
						
					</template>
					
				</el-table-column>
			</el-table>
			<!-- 分页器 -->
			<el-pagination
				background
				layout="prev, pager, next, jumper"
				v-model:current-page="params.pageNo"
				:page-count="tableData.pages"
				:total="tableData.total"
				style="margin-top: 40px;"
				@current-change="getTableData"
			></el-pagination>
		</div>
		<!-- 添加修改的对话框 -->
		<el-dialog
			v-model="dialog.show"
			:title="dialog.title"
			width="700px"
			:close-on-click-modal="false">
			<Dialog
				:categoryList="categoryList"
				v-if="dialog.show"
				@getTableData="getTableData"
				v-model:show="dialog.show"
				:id="dialog.id"
				:level="dialog.level"
				:parentId="dialog.parentId"
			></Dialog>
		
		</el-dialog>
    </div>
</template>

<script setup>
import { Search } from '@element-plus/icons-vue'
import { copy } from 'copy-anything'
import { reactive, ref} from 'vue'
import { get, post } from '@/plugins/axios'
import url from './pathUtil'
import { ElMessage, ElMessageBox } from 'element-plus';
import Dialog from './dialog'

/* -------------------------数据部分------------------------------ */
//ref式响应数据一定要用.value来修改
let tableData = reactive({
	records: [],
	pages: 0,
	total: 0 
})
const TreeSelectProps = reactive({
	children: 'children',
	label: 'name', // 树节点显示的文本字段
	value: 'id' // 绑定的值字段
})
//存储类别列表
const categoryList = ref([])
const params = reactive({
    categoryId: -1,
	pageNo: 1,
	pageSize: 10
})
let searchCategory = ref()
console.dir(searchCategory)
const formObj = null
const dialog = reactive({
	title: '',
	id: '',
	show: false,
	parentId: null,
	level: null
})
const searchValue = ref('')
/* -------------------------函数部分------------------------------ */
//得到类别数据
getCategoryList()
function getCategoryList() {
	get('/category/list', params, content => {
		categoryList.value = content
	})
}
//获取表格数据
getTableData()
function getTableData() {
	get(url.list, params, content => {
		//console.dir(content)
		tableData.records = copy(content.records)
		tableData.pages = content.pages
		tableData.total = content.total
	})
}
function getByCategoryId() {
    params.categoryId = searchCategory
    get(url.list, params, content => {
        tableData.records = copy(content.records)
		tableData.pages = content.pages
		tableData.total = content.total
    })
}
//类别map
function categoryFormatter(row, column, cellValue, index) {
	const name = findName(cellValue, categoryList.value)
	return name
}

function findName(target, table) {
	//console.log(target, table)
	for(let i = 0; i < table.length; i++) {
		if(table[i].children.length > 0) {
			//递归再次调用 查询子节点
			let name = findName(target, table[i].children)
			if (name) { // 如果在子节点中找到了，直接返回
			    return name;
			}
		}
		//console.dir(table[i].name)
		if(table[i].id === target) {
			return table[i].name
		}
	}
	return undefined
}
//删除
function del(id) {
	if(null != id) {
		const text = '确定要删除该商品吗'
		ElMessageBox.confirm(text, '警告', {
			type: 'warning'
		}).then(() => {
			post(url.del, { id }, content => {
				getTableData()
			},formObj)
		})
	}
}
//添加 传参为了后续给数据库相应的参数
function add(parentId, level) {
	dialog.title = '添加商品'
	dialog.show = true
	dialog.id = null
	dialog.level = level
	dialog.parentId = parentId
}
//修改
function update(id) {
	dialog.id = id
	dialog.title = '修改商品'
	dialog.show = true
}
//修改状态
function updateStatus(id, status) {
	const text = status ? '确定要上架该商品吗?' : '确定要下架该商品吗'
	ElMessageBox.confirm(text, '警告', {
		type: 'warning'
	}).then(() => {
		post(url.updateStatus, { id, status }, content => {
			getTableData()
		})
	}).catch(() => {})
}
//搜索
function search() {
	//去除全部空格
    if (searchValue.value.trim() !== '') {
        console.log(searchValue.value)
        get(url.searchByName, { searchValue: searchValue.value, pageNo: params.pageNo, pageSize: params.pageSize }, content => {
            tableData.records = copy(content.records)
            tableData.pages = content.pages
            tableData.total = content.total
        })
	}else {
		ElMessage({
			message: '您的输入框为空，已为您展示全部数据',
			type: 'warning'
        })
        getTableData()
	}
}
// //查找函数
// function find(target, table) {
// 	for(let i = 0; i < table.length; i++) {
// 		//查询逻辑
// 		if(table[i].name.indexOf(target) < 0) {
// 			table.splice(i, 1)
// 			i--;
// 		}
// 	}
// }
//获取第一张图片路径
function getImagePathFirst(list) {
	let path = ''
	if(list.length > 0) {
		path = 'http://localhost:9000' + list[0]
	}else {
		path = ''
	}
	return path
}
//获取全部图片路径
function getImagePath(list) {
	let imageList = []
	for(let i in list) {
		let path = 'http://localhost:9000' + list[i]
		imageList.push(path)
	}
	return imageList
}
</script>

<style lang="scss" scoped>
.wrapper{
	height: 80vh;
	.util{
		width: 100%;
		height: 50px;
		background-color: #ffffff;
		border-radius: 4px;
		margin-bottom: 20px;
		box-shadow: 2px 2px 10px rgba(0,0,0,0.2);
		display: flex;
		align-items: center;
	}
	.main{
		width: 100%;
		padding: 15px;
		
		background-color: #ffffff;
		border-radius: 4px;
		box-shadow: 2px 0px 10px rgba(0,0,0,0.2);
		overflow: hidden;
		.el-table-price{
			text-align: center;
			.cell {
				text-align: center;
			}
		}
	}
}
</style>